package com.leyou.user.web;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/info")
public class UserController {

    @Autowired
    private UserService userService;

    //判断信息是否存在
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> msgExist(@PathVariable("data") String data, @PathVariable("type") Integer type) {
        Boolean bool = userService.msgExist(data, type);
        return ResponseEntity.ok().body(bool);
    }

    //发送短信功能
    @PostMapping("code")
    public ResponseEntity<Void> sendMsg(@RequestParam("phone") String phone){
        try {
            userService.sndMsg(phone);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(400).build();
        }

    }

    //用户注册
    @PostMapping
    public ResponseEntity<Void> userRegister(
            @Valid User user,
            BindingResult result,
            @RequestParam("code") String code
    ) {
        if (result.hasErrors()) {
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400, msg);
        }
        userService.userRegister(user.getUsername(), user.getPassword(), user.getPhone(), code);
        return ResponseEntity.ok().build();
    }


    //根据用户名和密码查询
    @GetMapping
    public ResponseEntity<UserDTO> quereyByUserNameAndPassword(@RequestParam("username") String userName, @RequestParam("password") String password){
        return ResponseEntity.ok().body(userService.quereyByUserNameAndPassword(userName, password));
    }

    //展示当前用户登录信息
    @GetMapping("me")
    public ResponseEntity<UserDetail> me(){
        return ResponseEntity.ok(UserContext.getUser());
    }
}
